package com.lfg.leetcode.leetcode0;

public class No63uniquePathsWithObstacles {

    public static void main(String[] args) {
        int[][] nums = new int[1][1];
        nums[0][0] = 1;
        int ret = uniquePathsWithObstacles(nums);
        System.out.println(ret);
    }

    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        if (m == 0) {
            return 1;
        }
        int n = obstacleGrid[0].length;
        if (n == 0) {
            return 1;
        }
        if (obstacleGrid[m - 1][n - 1] == 1) {
            return 0;
        }
        obstacleGrid[m - 1][n - 1] = 1;


        for (int y = n - 2; y >= 0; y--) {
            if (obstacleGrid[m - 1][y] != 1) {
                obstacleGrid[m - 1][y] = obstacleGrid[m - 1][y + 1];
            } else {
                obstacleGrid[m - 1][y] = 0;
            }
        }
        for (int x = m - 2; x >= 0; x--) {
            if (obstacleGrid[x][n - 1] != 1) {
                obstacleGrid[x][n - 1] = obstacleGrid[x + 1][n - 1];
            } else {
                obstacleGrid[x][n - 1] = 0;
            }
        }
        for (int x = m - 2; x >= 0; x--) {
            for (int y = n - 2; y >= 0; y--) {
                if (obstacleGrid[x][y] == 1) {
                    obstacleGrid[x][y] = 0;
                    continue;
                }
                obstacleGrid[x][y] = obstacleGrid[x][y + 1] + obstacleGrid[x + 1][y];
            }
        }
        int ret = obstacleGrid[0][0];
        if (ret < 0) {
            return 0;
        }
        return ret;
    }
}

